package com.asm.controller;


import com.alibaba.fastjson.JSONObject;
import com.asm.mapper.Analysis2With3DMapper;
import com.asm.mapper.SampleInfo3DMapper;
import com.asm.pojo.*;
import com.asm.service.Analysis2With3DService;
import com.asm.util.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

@RestController
@CrossOrigin
@RequestMapping("/analysis2")
public class AnalysisChromatinInteraction {

    @Autowired
    private Path path;

    @Autowired
    private ExecLinux execLinux;

    @Autowired
    private Analysis2With3DService analysis2With3DService;
    @Autowired
    private SampleInfo3DMapper sampleInfo3DMapper;

    @GetMapping("/")
    public String hello(){
        return "正在访问analysis2接口，请阅读api文档后使用！！";
    }

    /**
     *         PageInfo 对象包含了丰富的分页信息：
     *         pageNum：当前页码
     *         pageSize：每页条数
     *         size：当前页记录数
     *         total：总记录数
     *         pages：总页数
     *         list：数据列表
     *         isFirstPage：是否第一页
     *         isLastPage：是否最后一页
     *         hasPreviousPage：是否有上一页
     *         hasNextPage：是否有下一页
     */
    @GetMapping("/analysis")
    public JSONObject Analysis2Distal(@RequestParam("chromosomalRegions") String chromosomalRegions) throws IOException{
        JSONObject result = new JSONObject();

        String[] chromosomalRegionsData = chromosomalRegions.split("\n");

        File file_chrom =new File("./distal.bed");
        if(!file_chrom.exists()){
            file_chrom.createNewFile();
        }
        // 创建表1 文件缓冲输出流
        BufferedWriter bw1 = new BufferedWriter(new FileWriter(file_chrom,true));
        // 写表1文件数据 遍历集合
        for (String data : chromosomalRegionsData) {
            String[] chrom = data.split(" ");
            StringBuilder chromRow = new StringBuilder();
            chromRow.append(chrom[0]).append("\t").append(chrom[1]).append("\t").append(chrom[2]);
            bw1.write(chromRow.toString());
            bw1.newLine();
        }
        bw1.close();

        //上传文件
        String path =this.path.getFileUploadPath();
        String randomName_chrom = UUID.randomUUID().toString();
        String resultName = randomName_chrom +".bed";
        String fileName_chrom = FileFr.upload(path,randomName_chrom,".bed",FileFr.fileMultipartFile(file_chrom));
        file_chrom.delete();
        //上传r执行命令
        String command = null;
        try {
            Shell shell = new Shell(execLinux);
            command = shell.execCommand("conda activate base;cd /home/jmzhao/CanASM/runfile/static;bedtools intersect -a snv_cpg.bed -b /home/jmzhao/CanASM/runfile/uploadfile/"+fileName_chrom+" > /home/jmzhao/CanASM/runfile/resultfile/"+resultName);
//            command = shell.execCommand("conda activate base;cd /home/CanASM/runfile/static;bedtools intersect -a snv_cpg.bed -b /home/CanASM/runfile/uploadfile/"+fileName_chrom+" > /home/CanASM/runfile/resultfile/"+resultName);

        } catch (Exception e) {
            e.printStackTrace();
        }

        String fileResultpath =this.path.getResultFilePath()+resultName;
        File file = new File(fileResultpath);
        BufferedReader br = new BufferedReader(new FileReader(file));
        String s,index = "";
        while ((s = br.readLine()) != null) {
            String[] sline = s.split("\n");
            String[] sIndex = sline[0].split("\t");
//            int num = Integer.parseInt(sIndex[3]);
            String snv = sIndex[3].toString();
            index = snv + "," + index;
        }
        br.close();
        String[] indexId = index.split(",");
        for (String id:
                indexId) {
            System.out.println(id);
        }
//        List<Analysis2With3D> Distal = analysis2With3DService.getDistal(indexId);
//        List<Analysis2With3D> Proximal = analysis2With3DService.getProximal(indexId);
//
//        result.put("Distal",Distal);
//        result.put("Proximal",Proximal);
        result.put("snv",indexId);
        result.put("command",command);
        return result;
    }


    @GetMapping("/getDiatal")
    public List<Analysis2With3D> getDistal(@RequestParam("snvList") String[] snvList,
                                @RequestParam("pageNum") int pageNum,
                                @RequestParam("pageSize") int pageSize,
                                @RequestParam("tissue")String tissue){
        pageSize = 10000000;
        if (tissue.equals("ALL")){
            tissue = null;
        }
        return analysis2With3DService.getDistal(snvList,pageNum,pageSize,tissue);
    }
    @GetMapping("/getProximal")
    public List<Analysis2With3D> getProximal(@RequestParam("snvList")  String[] snvList,
                                                             @RequestParam("pageNum") int pageNum,
                                                             @RequestParam("pageSize") int pageSize,
                                             @RequestParam("tissue")String tissue){
        pageSize = 10000000;
        if (tissue.equals("ALL")){
            tissue = null;
        }
        return analysis2With3DService.getProximal(snvList, pageNum, pageSize,tissue);
    }

    @GetMapping("/plot")
    public JSONObject analysis2_plot(@RequestParam("snv") String snv,@RequestParam("tissue")String tissue){
        if (tissue.equals("ALL")){
            tissue = null;
        }
        JSONObject result = new JSONObject();
        List<MergedInter> results = analysis2With3DService.getMergedInter(snv);
        List<Anchor> anchors = new ArrayList<>();
        List<Analysis2With3D> Distal = analysis2With3DService.getDistalBySnv(snv,tissue);
        List<Analysis2With3D> Proximal = analysis2With3DService.getProximalBySnv(snv,tissue);
        // 合并两个列表
        List<Analysis2With3D> combinedResults = new ArrayList<>(Distal);
        combinedResults.addAll(Proximal);
        // 排序
//        Collections.sort(combinedResults, (a1, a2) -> a1.getId().compareTo(a2.getId()));

//        画图所需要的数据格式
        for (MergedInter item : results) {
            String start = item.getAnchor1Start();
            String end = item.getAnchor1End();
            anchors.add(new Anchor("anchor1", "anchor", start, end, item.getChr(), item.getId()));

            start = item.getAnchor2Start();
            end = item.getAnchor2End();
            anchors.add(new Anchor("anchor2", "anchor", start, end, item.getChr(), item.getId()));
        }
        result.put("anchors",anchors);
        result.put("mainData",combinedResults);
        return result;
    }

// 未修改
    @GetMapping("/SampleInfo3D")
    public List<SampleInfo3D> SampleInfo3D(@RequestParam("sample") String sample) throws IOException{

        List<SampleInfo3D> SampleInfo3D = sampleInfo3DMapper.getSampleInfo3DBySample(sample);

        return SampleInfo3D;
    }
    @GetMapping("/distal_snv")
    public JSONObject Analysis2DistalBySNV(@RequestParam("snv") String snv) throws IOException {
        JSONObject result = new JSONObject();

        String[] snvList = snv.split("\n");

        List<Analysis2With3D> Distal = analysis2With3DService.getDistalBySnvList(snvList);
        List<Analysis2With3D> Proximal = analysis2With3DService.getProximalBySnvList(snvList);

        result.put("Distal", Distal);
        result.put("Proximal", Proximal);
        result.put("snv", snvList);
        return result;
    }

}
